package Day2025_02_18;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LeetCode18 {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        ArrayList<List<Integer>> lists = new ArrayList<>();
        for (int l = nums.length - 1; l > 2; l--) {
            long tmp = (long) target - nums[l];
            for (int k = l - 1; k > 1; k--) {
                int i = 0, j = k - 1;
                while (i < j) {
                    long sum = (long) nums[i] + nums[j] + nums[k];
                    if (sum > tmp) j--;
                    else if (sum < tmp) i++;
                    else {
                        lists.add(new ArrayList(Arrays.asList(nums[i], nums[j], nums[k], nums[l])));
                        i++; j--;
                        while (i < j && nums[i] == nums[i - 1]) i++;
                        while (i < j && nums[j] == nums[j + 1]) j--;
                    }
                }
                while (k > 1 && nums[k] == nums[k - 1]) k--;
            }
            while (l > 2 && nums[l] == nums[l - 1]) l--;
        }
        return lists;
    }
}
